
import UIKit
import CoreLocation
import WebKit

import MapKit

class XWMapViewController: UIViewController {
    private var locationManager:CLLocationManager!
    @IBOutlet weak var XWMapView: MKMapView!
    
    
    @IBOutlet weak var XWCountryImageView: UIImageView!
    
    @IBOutlet weak var XWCountryLabel: UILabel!
    
    @IBOutlet weak var XWCityLabel: UILabel!
    
    @IBOutlet weak var XWLongitudeLabel: UILabel!
    
    @IBOutlet weak var XWLatitudeLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        showUI()
        
    }
    
    @IBAction func XWBackButtonClick(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}
extension XWMapViewController:CLLocationManagerDelegate,MKMapViewDelegate{
    private func showUI() {
        createMap()
        XWCountryImageView.sd_setImage(with: URL.init(string: XWDataStateTool.shareManger.getXWNodeInfoModel().flag ?? ""), placeholderImage:UIImage.init(named: "logo_default") )
        XWCountryLabel.text = XWDataStateTool.shareManger.getXWNodeInfoModel().country
    }
    private func createMap() {
        XWMapView.delegate = self
        XWMapView.mapType = .standard
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            locationManager.requestLocation()
        }
        
    }
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            let latitude = location.coordinate.latitude
            let longitude = location.coordinate.longitude
            let initialLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
            let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
            let region = MKCoordinateRegion(center: initialLocation, span: span)
            XWMapView.setRegion(region, animated: true)
            XWLongitudeLabel.text = "Longitude:" + String(longitude)
            XWLatitudeLabel.text = "Latitude:" + String(latitude)
            let geocoder = CLGeocoder()
            geocoder.reverseGeocodeLocation(location) {[self] (placemarks, error) in
                if let placemarks = placemarks {
                    let placemark = placemarks[0]
                    XWCityLabel.text = "City:"+placemark.locality!+"   Region:"+placemark.country!
                }
            }
        }
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
        printLog(error)
    }
}
